const  loadImg = urlId => {
    const url = `https://www.image.com/${urlId}`
    
    return new Promise((resolve, reject) => {
        // const img = new Image();
        // img.onerror = function() {
        //     reject(urlId);
        // }

        // img.onload = function() {
        //     resolve(urlId);
        // }

        // img.src = url;
        // console.log(url);
        setTimeout(() => {
            resolve(urlId);
        }, 200);
    })
}

const urlIds = [2, 3, 4, 5, 6, 7, 8, 9];

// urlIds.reduce((prevPromise, urlId) => {
// }
// loaImgOneByOne();

// 如果要求提高效率，将所有图片的请求一次性发出
// const promiseArray = urlIds.map(urlId => loadImg(urlId));

// Promise.all(promiseArray)
//     .then(() => {
//         console.log('finish laod all');
//     })
//     .catch((error) => {
//         console.log(error);
//     })

// 继续提出需求，我们希望控制最大并发数为 3，最多 3 个请求一起发出，剩下 2 个一起发出，
const loadByLimit = (urlIds, loadImg, limit) => {
    const urlIdsCopy = [...urlIds];

    if (urlIdsCopy.length <= limit) {
        // 如果数组长度小于最大并发数，直接全部请求
        const promiseArray = urlIds.map(urlId => loadImg(urlId));
        return Promise.all(promiseArray);
    }

     // 注意 splice 方法会改变 urlIdsCopy 数组
    const promiseArray = urlIdsCopy.splice(0, limit).map(urlId => loadImg(urlId));
    // console.log('promiseArray', promiseArray)

    // 每次 reduce 返回的值都会作为下次 reduce 回调函数的第一个参数，直到队列循环完毕
    urlIdsCopy.reduce(
        (prevPromise, urlId) => 
            {
                // console.log(prevPromise)
                return prevPromise
                        .then(() => Promise.race(promiseArray))
                        .catch(error => { console.log(error) })
                        .then(resolvedId => {
                            console.log('resolvedId', resolvedId);
                            // 将 resolvedId 剔除出 promiseArray 数组
                            // 这里的删除只是伪代码，具体删除情况要看后端 Api 返回结果
                            let resolveIdPostion = promiseArray.findIndex(id => resolvedId === id);
                            promiseArray.splice(resolveIdPostion, 1);
                            // console.log('splice', promiseArray)
                            promiseArray.push(loadImg(urlId));
                        })
            }
        ,
       Promise.resolve()
    )
    .then(() => {
        console.log('promiseArray===', promiseArray)
        Promise.all(promiseArray)
    });
}

loadByLimit(urlIds, loadImg, 3)

    // .then(res => { console.log(res) })
    // .catch(error => { console.log(error) });